#!/usr/bin/env python
#coding=utf8

import os
import sys
import httplib
import fcgiapp
from xml.etree import ElementTree

def lineno():
    frame = None
    try:
        raise ZeroDivisionError
    except ZeroDivisionError:
        frame = sys.exc_info()[2].tb_frame.f_back
    return frame.f_lineno

def sct_print(str):
    os.system("echo" + " \""+ str +"\" " + "> /dev/pts/16")

sct_print("%s:%d:%s"%(__file__, lineno(),"print by sct"))
    
num = 2
while 1:
    (input, output, error, environ) = fcgiapp.Accept()
    try:
        httpClient = httplib.HTTPConnection('127.0.0.1', 8800, timeout=30)
        httpClient.request('GET', '/')

        #response是HTTPResponse对象
        response = httpClient.getresponse()
        ctx = response.read()
        
#         sct_print(ctx)
        
        output.write('Content-type: text/xml\r\n\r\n'+ctx)
        
        num = num+1
        if num > 100:
            num = 2
        
        ipStr= "%s%d" % ("192.168.1.", num)
       
        xmldoc = ElementTree.fromstring(ctx)
        
        for el in xmldoc.findall("./rtsp/urls/url[@id='ts']/addr"):
                el.text = ipStr
       
        ctx = ElementTree.tostring(xmldoc, encoding="utf8", method="xml")
#         sct_print(ctx)
        
        httpPost = httplib.HTTPConnection('127.0.0.1', 8800, timeout=30)
        httpPost.request('POST', '/rtsp/urls/ts/addr', ctx) 
        response = httpPost.getresponse()
        
    except IOError:
        sct_print("XML FIle Dose not Exist!")
        
    except Exception, e:
        sct_print("error happen!!")
    
    finally:
        if httpClient:
            httpClient.close()
            
        if httpPost:
            httpPost.close()
    
        fcgiapp.Finish() 
    
    #output.write('Content-type: text/html\r\n\r\n<title>FastCGI Hello on Android!</title><h1>FastCGI Hello!</h1>')